package com.example.controller;

import com.example.client.OrderClient;
import com.example.client.PaymentClient;
import com.example.common.Result;
import com.example.entity.Order;
import com.example.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/demo")
@Slf4j
public class DemoController {
    private final PaymentClient paymentClient;
    private final OrderClient orderClient;

    public DemoController(PaymentClient paymentClient, OrderClient orderClient) {
        this.paymentClient = paymentClient;
        this.orderClient = orderClient;
    }

    @GetMapping("/test")
    public Result<String> test() {
        // 测试支付服务
        String paymentPort = paymentClient.getPort();
        log.info("Payment service port: {}", paymentPort);

        // 测试订单服务
        String orderPort = orderClient.getPort();
        log.info("Order service port: {}", orderPort);

        return Result.success("Payment Port: " + paymentPort + ", Order Port: " + orderPort);
    }

    @PostMapping("/create-order-and-pay")
    public Result<Order> createOrderAndPay(@RequestBody Order order) {
        // 1. 创建订单
        Result<Order> orderResult = orderClient.create(order);
        if (orderResult.getCode() != 200) {
            return Result.error("创建订单失败");
        }
        Order createdOrder = orderResult.getData();
        log.info("Created order: {}", createdOrder);

        // 2. 创建支付
        Payment payment = new Payment(null, "PAY" + createdOrder.getOrderNo(), createdOrder.getAmount());
        Result<Payment> paymentResult = paymentClient.create(payment);
        if (paymentResult.getCode() != 200) {
            return Result.error("创建支付失败");
        }
        log.info("Created payment: {}", paymentResult.getData());

        // 3. 支付订单
        Result<Order> payResult = orderClient.pay(createdOrder.getId());
        if (payResult.getCode() != 200) {
            return Result.error("支付订单失败");
        }

        return Result.success(payResult.getData());
    }
} 